const WebSocket = require('ws');

/**
 * 测试物品图片更新效果
 * 验证1120和1199指令是否正确返回更新后的图片信息
 */

class ItemsPicTester {
    constructor() {
        this.ws = null;
        this.characterId = 1001; // 测试角色ID
    }

    async connect() {
        return new Promise((resolve, reject) => {
            console.log('🔌 连接WebSocket服务器...');

            this.ws = new WebSocket('ws://localhost:3001');

            this.ws.on('open', () => {
                console.log('✅ WebSocket连接成功');
                resolve();
            });

            this.ws.on('error', (error) => {
                console.error('❌ WebSocket连接失败:', error.message);
                reject(error);
            });

            this.ws.on('message', (data) => {
                try {
                    const message = JSON.parse(data.toString());
                    this.handleMessage(message);
                } catch (error) {
                    console.error('❌ 解析消息失败:', error.message);
                }
            });
        });
    }

    handleMessage(message) {
        console.log('\n📨 收到消息:', JSON.stringify(message, null, 2));

        if (message.act_id === 1120) {
            console.log('\n🔍 分析1120宝物商店响应:');
            this.analyzeItemsList(message, '宝物商店');
        } else if (message.act_id === 1199) {
            console.log('\n🔍 分析1199经验商店响应:');
            this.analyzeItemsList(message, '经验商店');
        }
    }

    analyzeItemsList(message, shopType) {
        if (message.code === 0) {
            console.log(`✅ ${shopType}查询成功`);
            console.log(`📊 物品数量: ${message.list ? message.list.length : 0}`);

            if (message.list && message.list.length > 0) {
                console.log(`\n📋 ${shopType}物品列表分析:`);

                let itemsWithPic = 0;
                let itemsWithoutPic = 0;

                message.list.forEach((item, index) => {
                    console.log(`\n物品 ${index + 1}:`);
                    console.log(`  - ID: ${item.id}`);
                    console.log(`  - 名称: ${item.name}`);
                    console.log(`  - 图片: ${item.pic || '无'}`);
                    console.log(`  - 价格: ${item.price || '无'}`);
                    console.log(`  - 描述: ${item.descr ? item.descr.substring(0, 50) + '...' : '无'}`);

                    if (item.pic && item.pic !== '') {
                        console.log('  ✅ 有图片');
                        itemsWithPic++;
                    } else {
                        console.log('  ❌ 无图片');
                        itemsWithoutPic++;
                    }
                });

                console.log(`\n📊 ${shopType}图片统计:`);
                console.log(`  - 有图片: ${itemsWithPic} 个`);
                console.log(`  - 无图片: ${itemsWithoutPic} 个`);
                console.log(`  - 图片覆盖率: ${((itemsWithPic / message.list.length) * 100).toFixed(1)}%`);

                // 检查分页信息
                if (message.page !== undefined) {
                    console.log(`\n📄 分页信息:`);
                    console.log(`  - 当前页: ${message.page}`);
                    console.log(`  - 总页数: ${message.sum || '未知'}`);
                }

            } else {
                console.log(`📭 ${shopType}没有物品`);
            }

        } else {
            console.log(`❌ ${shopType}查询失败`);
            console.log(`错误信息: ${message.msg || '未知错误'}`);
        }
    }

    async testTreasureShop() {
        try {
            console.log('\n🧪 测试1120宝物商店查询...');

            // 发送1120查询请求
            const request = {
                c: 1120,
                d: {
                    pageNum: 0
                }
            };

            console.log('📤 发送请求:', JSON.stringify(request, null, 2));
            this.ws.send(JSON.stringify(request));

            // 等待响应
            await new Promise(resolve => setTimeout(resolve, 2000));

        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        }
    }

    async testExpShop() {
        try {
            console.log('\n🧪 测试1199经验商店查询...');

            // 发送1199查询请求
            const request = {
                c: 1199,
                d: {
                    pageNum: 0
                }
            };

            console.log('📤 发送请求:', JSON.stringify(request, null, 2));
            this.ws.send(JSON.stringify(request));

            // 等待响应
            await new Promise(resolve => setTimeout(resolve, 2000));

        } catch (error) {
            console.error('❌ 测试失败:', error.message);
        }
    }

    async runTests() {
        try {
            await this.connect();

            // 等待连接稳定
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 测试宝物商店
            await this.testTreasureShop();

            // 等待一下再测试经验商店
            await new Promise(resolve => setTimeout(resolve, 1000));

            // 测试经验商店
            await this.testExpShop();

            console.log('\n🎉 测试完成');

        } catch (error) {
            console.error('❌ 测试执行失败:', error.message);
        } finally {
            if (this.ws) {
                this.ws.close();
                console.log('🔌 WebSocket连接已关闭');
            }
        }
    }
}

// 执行测试
if (require.main === module) {
    const tester = new ItemsPicTester();
    tester.runTests()
        .then(() => {
            console.log('\n✅ 物品图片更新测试完成');
            process.exit(0);
        })
        .catch((error) => {
            console.error('\n❌ 物品图片更新测试失败:', error.message);
            process.exit(1);
        });
}

module.exports = { ItemsPicTester };
